﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebAPI中实现属性注入.Attributes;
using WebAPI中实现属性注入.Services;

namespace WebAPI中实现属性注入.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        // 标记需要注入的属性
        [Inject]
        public ILoggerService Logger { get; set; }

        [Inject]
        public IUserService UserService { get; set; }

        // 假设由于某种限制，无法修改此构造函数
        public UserController()
        {
        }

        [HttpGet("{id}")]
        public IActionResult GetUser(int id)
        {
            // 验证注入是否成功（属性注入必要的安全检查）
            if (Logger == null)
                throw new InvalidOperationException("Logger服务未注入");

            if (UserService == null)
                throw new InvalidOperationException("UserService服务未注入");

            Logger.LogInformation($"获取用户信息，ID: {id}");
            var userName = UserService.GetUserName(id);

            return Ok(new { UserId = id, UserName = userName });
        }
    }
}
